/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bean;

import com.model.LoginController;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Tuan Long
 */
@Named(value = "login")
@SessionScoped
public class Login implements Serializable {

    private String realname;

    public String getRealname() {
        return realname;
    }

    public void setRealname(String realname) {
        this.realname = realname;
    }
    private String username;
    private String password;
    private boolean logged;
    private boolean message;

    public boolean isMessage() {
        return message;
    }

    public void setMessage(boolean message) {
        this.message = message;
    }

    public boolean isLogged() {
        return logged;
    }

    public void setLogged(boolean logged) {
        this.logged = logged;
    }

    public Login() {
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String action() {
        LoginController control = new LoginController();
        String name = control.loginControl(username, password);
        if (name != null) {
            logged = true;
            realname = name;
            SaveLoginToSession(name);
            return "index?faces-redirect=true";
        } else {
            message = true;
            return "login?faces-redirect=true";
        }

    }

    private void SaveLoginToSession(String realname) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
        Login user = new Login();
        user.setUsername(username);
        user.setLogged(logged);
        user.setPassword(password);
        user.setRealname(realname);
        session.setAttribute("login", user);
    }

    public String logout() {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpSession session = (HttpSession) request.getSession(true);
        session.setAttribute("login", null);
        return "login?faces-redirect=true";
    }
}
